import axios from 'axios'

export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  getters: {
    total ({ list }) {
      return list.reduce((p, c) => p + c.count, 0)
    },
    totalPrice ({ list }) {
      return list.reduce((p, c) => p + c.count * c.price, 0)
    }
  },
  mutations: {
    updateList (state, payload) {
      state.list = payload
    },
    updateCount (state, { id, count }) {
      const item = state.list.find(item => item.id === id)
      item.count = count
    }
  },
  actions: {
    async getList ({ commit }) {
      const { data } = await axios.get('http://localhost:8081/cart')
      commit('updateList', data)
    },
    async changeCount ({ dispatch }, { id, count }) {
      await axios.patch('http://localhost:8081/cart/' + id, { count })
      dispatch('updateCount')
    }
  }

}
